from django.shortcuts import render
from rest_framework import filters
from drf_haystack.viewsets import HaystackViewSet
from rest_framework.generics import ListAPIView


from .models import SKU
from . import serializers


# 熱門商品類視圖
class HotSkuListView(ListAPIView):
    serializer_class = serializers.HotSkuListSerializers
    pagination_class = None

    def get_queryset(self):
        category_id = self.kwargs.get("category_id")
        skus = SKU.objects.filter(category_id=category_id).order_by("-sales")[:2]
        return skus

    # def get(self,request,category_id):
    #     #1,获取对象
    #     queryset = self.get_queryset()
    #
    #     #2,获取序列化器
    #     serializer = self.get_serializer(instance=queryset,many=True)
    #
    #     #3,返回数据
    #     return Response(serializer.data)


# 商品列表類視圖
class SkuListView(ListAPIView):
    serializer_class = serializers.HotSkuListSerializers


    # 设置过滤后端,排序字段
    filter_backends = (filters.OrderingFilter,)
    ordering_fields = ('create_time', 'price', "sales")

    def get_queryset(self):
        # 獲取分類編號
        category_id = self.kwargs.get("category_id")
        # 根據編號查詢數據
        skus = SKU.objects.filter(category_id=category_id)
        return skus


class SKUSearchViewSet(HaystackViewSet):
    """
    SKU搜索
    """
    #1,数据集
    index_models = [SKU]

    #2,序列化器
    serializer_class = serializers.SKUIndexSerializer